<?php

namespace baidu;

use think\facade\Db;
use think\exception\ValidateException;

/**
 * 百度 AI 开放平台
 */
class Ai
{
    private $apiKey = '';
    private $secretKey = '';
    private $planId = '11663';   // 方案的id信息，请在人脸实名认证控制台查看创建的H5方案的方案ID信息
    private $accessToken = '';
    private $expires_in = 0;
    private $error = '';

    public function __construct()
    {
        $ai = Db::name('baidu_ai')
            ->where('id', 1)
            ->find();
        if (empty($ai)) {
            throw new ValidateException('百度 AI 账号未配置');
        }

        $this->apiKey = $ai['api_key'];
        $this->secretKey = $ai['secret_key'];
        $this->accessToken = $ai['access_token'];
        $this->expires_in = $ai['expires_in'];
    }

    /**
     * 获取 Access Token
     * 
     * https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
     */
    public function getAccessToken()
    {
        $now = time();
        if ($this->accessToken && $this->expires_in > $now) {
            return $this->accessToken;
        }

        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $params = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->apiKey,
            'client_secret' => $this->secretKey,
        ];
        $res = curlPost($url, http_build_query($params));
        $res = json_decode($res, true);
        if (empty($res['access_token'])) {
            $this->error = '百度 AccessToken 获取失败：' . json_encode($res, JSON_UNESCAPED_UNICODE);
            return false;
        }
        $this->accessToken = $res['access_token'];
        $this->expires_in = $res['expires_in'] + $now - 3600;
        Db::name('baidu_ai')
            ->where('id', 1)
            ->update([
                'access_token' => $this->accessToken,
                'expires_in' => $this->expires_in,
            ]);
        return true;
    }

    /**
     * 获取 verify_token
     * 
     * https://ai.baidu.com/ai-doc/FACE/aknovy94h
     */
    public function getVerifyToken()
    {
        if (false === $this->getAccessToken()) {
            return false;
        }

        $url = 'https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/verifyToken/generate?access_token=' . $this->accessToken;
        $params = [
            'plan_id' => $this->planId,
        ];
        $header = [
            'Content-Type: application/json'
        ];
        $res = curlPost($url, json_encode($params), $header);
        $res = json_decode($res, true);
        if (!empty($res['result']['verify_token'])) {
            return $res['result']['verify_token'];
        }
        $this->error = '获取 verify_token 失败：' . json_encode($res, JSON_UNESCAPED_UNICODE);
        return false;
    }

    /**
     * 指定用户信息上报接口
     */
    public function idcardSubmit($params)
    {
        $url = 'https://brain.baidu.com/solution/faceprint/idcard/submit';
        $params = [
            'verify_token' => $params['verify_token'],
            'id_name' => $params['id_name'],
            'id_no' => $params['id_no'],
            'certificate_type' => $params['certificate_type'],
        ];
        $header = [
            'Content-Type: application/json'
        ];
        $res = curlPost($url, json_encode($params), $header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 查询认证结果接口
     */
    public function resultDetail($verifyToken)
    {
        if (false === $this->getAccessToken()) {
            return false;
        }

        $url = 'https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/detail?access_token=' . $this->accessToken;
        $params = [
            'verify_token' => $verifyToken,
        ];
        $header = [
            'Content-Type: application/json'
        ];
        $res = curlPost($url, json_encode($params), $header);
        $res = json_decode($res, true);

        return $res;
    }

    public function getError()
    {
        return $this->error;
    }
}
